#include <QSettings>
#include "RecentFiles.h"
#include "RecentFilesIOQSettings.h"

RecentFilesIOQSettings* RecentFilesIOQSettings::clone() const
{
    return new RecentFilesIOQSettings(*this);
}

void RecentFilesIOQSettings::read(RecentFiles& recentFiles)
{
    QSettings settings;
    QStringList list;

    recentFiles.clear();
    settings.beginGroup("recentFiles");
    int num = settings.beginReadArray("list");

    for (int i = 0; i < num; ++i)
    {
        settings.setArrayIndex(i);
        list.append(settings.value("recentFile").toString());
    }

    settings.endArray();
    settings.endGroup();

    recentFiles.setList(list);
}

void RecentFilesIOQSettings::write(const RecentFiles& recentFiles)
{
    QSettings settings;
    const QStringList& list = recentFiles.list();

    if (!list.empty())
    {
        int i = 0;

        // Erase previous recent files.
        settings.beginGroup("recentFiles");
        settings.remove("");
        settings.endGroup();

        // Write out the new recent files.
        settings.beginGroup("recentFiles");
        settings.beginWriteArray("list");
        foreach(QString filename, list)
        {
            settings.setArrayIndex(i++);
            settings.setValue("recentFile", filename);
        }
        settings.endArray();
        settings.endGroup();
    }
}
